﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infrastructure;
using DormMS.IService;
using DormMS.Model.SearchModels;
using DormMS.Service;
using DormMS.Model;
using DormMS.Model.ViewModels;
using DormMS.Model.Enum;
using Infrastructure.Tool;
using SqlSugar;
using Senparc.Weixin.MP.TenPayLibV3;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Xml.Linq;
using DormMS.IService.Common;

namespace DormMS.Controllers
{
    public class OrderController : BaseController
    {
        protected IOrderService _orderService;
        private IProductService  _proService;
        private IMemberService _memberService;
        private IFreightService _freightService;
        private IProductCategoryService _cateService;
        private IWxConfigService _configService;
        protected ILogService logService;
        public OrderController(IUserInfoService s, IOrderService orderService, IProductService proService, IMemberService memberService, IFreightService freightService, IProductCategoryService cateService,IWxConfigService configService,ILogService l) : base(s)
        {
            _orderService = orderService;
            _proService = proService;
            _memberService = memberService;
            _freightService = freightService;
            _cateService = cateService;
            _configService = configService;
            logService = l;
        }

        #region 订单管理
        // GET: Order
        [HttpGet]
        public ActionResult OrderManage()
        {
            return View();
        }

        [HttpPost]
        public ActionResult OrderManage(OrderManageSearchModel search)
        {
            int total = 0;
            var list = _orderService.GetOrderManage(search, ref total);
            return Json(new { Total = total, Results = list });
        }

        public ActionResult OrderEdit()
        {
            return View();
        }


        public ActionResult OrderInfo()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetOrderInfo(int id)
        {
            var model = _orderService.GetOrderInfo(id);
            return Json(model);
        }

        [HttpPost]
        public ActionResult CheckOrder(List<string> CheckItemList)
        {
            return Json(Infrastructure.Result.Success());
        }

        public JsonResult GetProductList(ProductSearchModel seach)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                int total = 0;
                var list = _proService.GetProductSpecLsit(seach, ref total);
                result.data = list;
                result.count = total;
                result.isSuccess = true;

            }
            catch(Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetProductCateList()
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                var list = _cateService.GetCategoryList();
                result.data = list;
                result.isSuccess = true;

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetMemberList(string name)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                var list = _memberService.GetMemberInfoList("NickName like '%"+name+"%'");
                Member member = new Member();
                member.Id = 0;
                member.NickName = "匿名用户";
                list.Insert(0, member);
                result.data = list;
                result.isSuccess = true;

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //提交订单
        public JsonResult SaveOrder(Order order, List<SpecResponse> prolist)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                List<OrderDetail> odlist = new List<OrderDetail>();
                order.ProductPrice = 0;
                order.OrderPoint = 0;
                order.PostageMoney = _freightService.GetPostageMoney(prolist, order.ReceiveProvince);

                if (!order.ReceivePhone.IsMobile())
                {
                    result.msg="请输入正确的手机号";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }

                foreach (var item in prolist)
                {
                    OrderDetail od = new OrderDetail();

                    //od.OrderId = order.Id;
                    //od.OrderNo = order.OrderNo;
                    od.ProductName = item.Name;
                    od.ProductId = item.ProductId;
                    od.ProductSku = item.ProductSku;
                    od.ProductPrice = item.Price;
                    od.ProductCount = item.BuyCount;
                    od.SendStatus = OrderDetailSendStatus.未发货;
                    od.SpecId = item.Id;
                    od.SpecKey = item.SpecIds;
                    od.SpecName = item.SpecNames;
                    if (order.MemberDiscount.HasValue && order.MemberDiscount.Value > 0)
                    {
                        od.Discount = order.MemberDiscount.Value;
                        od.DiscountPrice = Generator.GetDisPrice(od.ProductPrice, od.Discount);
                    }
                    else
                    {
                        od.DiscountPrice = od.ProductPrice;
                    }

                    order.ProductPrice += od.DiscountPrice;

                    od.ImgUrl = item.ImgUrl;
                    od.MarketPrice = item.MarketPrice;
                    od.CostPrice = item.CostPrice;
                    od.Points = 0;
                    if (order.MemberId > 0)
                    {
                        var member = _memberService.GetMemberInfo(order.MemberId);
                        var level = _memberService.GetMemberLevelInfo(member.MemberLevel);
                        od.Points = (od.DiscountPrice * (level.OrderPoint * (decimal)0.01)).ToString("0").ObjToInt();
                        order.MemberName = member.NickName;
                    }
                    order.OrderPoint += od.Points;
                    odlist.Add(od);
                }

                if (order.Id > 0)
                {
                    if (order.OrderState == OrderStatus.待确认)
                    {

                    }
                    else
                    {
                        result.msg = "该订单"+order.OrderState.ToString()+",无法修改";
                    }
                }
                else
                {
                    order.OrderNo = _orderService.GetSerialNumber("W");
                    order.PayState = OrderPayStatus.未支付;
                    order.SendStatus = OrderSendStatus.未发货;
                    order.OrderState = OrderStatus.待确认;
                    order.OrderType = OrderType.正常订单;

                    order.OrderPrice = order.ProductPrice + order.PostageMoney;
                    order.PayMoney = order.ProductPrice + order.PostageMoney;
                    OrderRecord record = new OrderRecord();

                    record.OperationUserType = 1;
                    record.OperationId = CurrentLoginUser.Id;
                    record.ClientName = "后台";

                    int orderId = _orderService.AddOrder(order, odlist,record);
                   
                }
                result.isSuccess = true;

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //删除订单
        public JsonResult DelOrder(int id)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                OrderRecord or = new OrderRecord();
                or.OperationId = CurrentLoginUser.Id;
                or.ClientName = "后台";
                or.OperationUserType = 1;

                _orderService.DelOrder(id,or);
                result.isSuccess = true;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //取消订单
        public JsonResult CancelOrder(int id,string remark)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                OrderRecord or = new OrderRecord();
                or.OperationId = CurrentLoginUser.Id;
                or.ClientName = "后台";
                or.OperationUserType = 1;
                or.Remark = remark;

                _orderService.CancelOrder(id, or);
                result.isSuccess = true;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult PayOrder(string orderno, string note)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                OrderRecord or = new OrderRecord();
                or.OperationId = CurrentLoginUser.Id;
                or.ClientName = "后台";
                or.OperationUserType = 1;
                or.Remark = note;

                _orderService.PayOrder(orderno, or);
                result.isSuccess = true;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //确认订单
        public JsonResult ConfirmOrder(int id,string note)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                

                var order = _orderService.GetOrderInfo(id);
                if (order != null)
                {
                    if (order.PayState == OrderPayStatus.已支付)
                    {
                        if (order.OrderState == OrderStatus.待确认)
                        {
                            order.OrderState = OrderStatus.已确认;
                            _orderService.UpdateOrder(order);
                            OrderRecord or = new OrderRecord();
                            or.OperationId = CurrentLoginUser.Id;
                            or.ClientName = "后台";
                            or.OperationUserType = 1;
                            or.Remark = note;
                            or.OrderId = order.Id;
                            or.OrderNo = order.OrderNo;
                            or.PayStatus = order.PayState;
                            or.SendStatus = order.SendStatus;
                            or.OrderStatus = order.OrderState;
                            or.OperationNote = "确认订单";
                            _orderService.AddOrderRecord(or);
                            result.isSuccess = true;

                        }
                        else
                        {
                            result.msg = "订单已经不用确认了";
                        }
                    }
                    else
                    {
                        result.msg = "订单还未付款";
                    }
                }
                else
                {
                    result.msg = "订单不存在";
                }
                
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //取消确认
        public JsonResult CancelConfirmOrder(int id, string note)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                var order = _orderService.GetOrderInfo(id);
                if (order != null)
                {
                    if (order.OrderState == OrderStatus.已确认)
                    {
                        if (order.SendStatus == OrderSendStatus.未发货)
                        {
                            order.OrderState = OrderStatus.待确认;
                            _orderService.UpdateOrder(order);
                            OrderRecord or = new OrderRecord();
                            or.OperationId = CurrentLoginUser.Id;
                            or.ClientName = "后台";
                            or.OperationUserType = 1;
                            or.Remark = note;
                            or.OrderId = order.Id;
                            or.OrderNo = order.OrderNo;
                            or.PayStatus = order.PayState;
                            or.SendStatus = order.SendStatus;
                            or.OrderStatus = order.OrderState;
                            or.OperationNote = "取消确认订单";
                            _orderService.AddOrderRecord(or);
                            result.isSuccess = true;

                        }
                        else
                        {
                            result.msg = "订单已经发货，无法取消确认";
                        }
                    }
                    else
                    {
                        result.msg = "订单已无法取消确认";
                    }
                }
                else
                {
                    result.msg = "订单不存在";
                }
                
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetOrderModel(int id)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                result.data = _orderService.GetOrderModel(id);
                result.isSuccess = true;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetOrderDetail(int orderId)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                result.data = _orderService.GetV_OrderDetailByOrderId(orderId);
                result.isSuccess = true;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetOrderRecord(int orderId)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                result.data = _orderService.GetOrderRecord(orderId);
                result.isSuccess = true;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 发货单
        public ActionResult SendOrderList()
        {
            return View();
        }

        public ActionResult SendOrderInfo()
        {
            return View();
        }

        public JsonResult GetSendOrderList(OrderManageSearchModel search)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                int total = 0;
                var list = _orderService.GetSendOrderList(search, ref total);
                result.data = list;
                result.count = total;
                result.isSuccess = true;

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }


        public JsonResult GetSendOrderRecord(int orderId)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                var list = _orderService.GetDeliveryListByOrderId(orderId);
                result.data = list;
                result.isSuccess = true;

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult AddDelivery(Delivery model, int[] ids)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                model.AddUserId = CurrentLoginUser.Id;
                model.BestTime = DateTime.Now.AddDays(7);
                

                 _orderService.AddDelivery(model,ids);
                result.isSuccess = true;

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 积分订单
        public ActionResult PointOrderManage()
        {
            return View();
        }

        
        public ActionResult GetPointOrderList(OrderManageSearchModel search)
        {
            int total = 0;
            var list = _orderService.GetPointOrderManage(search, ref total);
            return Json(new { Total = total, Results = list });
        }
        #endregion

        #region 退货单
        public ActionResult ReturnGoodsManage()
        {
            return View();
        }

        public ActionResult GetReturnGoodsList(ReturnGoodsSearchModel search)
        {
            int total = 0;
            var list = _orderService.GetReturnGoodsManage(search, ref total);
            return Json(new { Total = total, Results = list });
        }

        public ActionResult ReturnGoodsInfo()
        {
            return View();
        }

        public JsonResult GetReturnGoodsInfo(int id)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                result.data = _orderService.FindReturnGoods(id);
                result.isSuccess = true;
            }
            catch(Exception ex)
            {
                result.msg = ex.Message; 
            }
            return Json(result);
        }

        public JsonResult SaveReturnGoods(ReturnGoods model)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                var entity = _orderService.GetReturnGoodsInfo(model.Id);
                var member = _memberService.GetMemberInfo(model.MemberId);
                var detail = _orderService.FindOrderDetail(model.OrderDetailId);
                if ((int)model.Satus > 1 && (int)entity.Satus > 1)
                {
                    result.msg = "该申请已处理完成，请勿重复处理";
                    return Json(result);
                }

                if (model.ReturnType == 0 && model.Satus == ReturnStatus.已换货)
                {
                    result.msg = "退货申请不能同意换货";
                    return Json(result);
                }
                if (model.ReturnType == 1 && (model.Satus == ReturnStatus.全部退款||model.Satus==ReturnStatus.部分退款))
                {
                    result.msg = "换货申请不能同意退款";
                    return Json(result);
                }

                entity.ReturnAmount = model.ReturnAmount;
                entity.ReturnType = model.ReturnType;
                entity.Remark = model.Remark;
                entity.UserId = CurrentLoginUser.Id;
                entity.Satus = model.Satus;

                if (entity.Satus == ReturnStatus.全部退款 || entity.Satus == ReturnStatus.部分退款)
                {
                    #region 退款
                    string return_code = "";
                    if (entity.ReturnAmount > 0)
                    {
                        var order = _orderService.GetOrderInfo(entity.OrderId);


                        decimal returnMoney = 0;
                        decimal pmoney = 0;
                        decimal mmoney = 0;
                        _orderService.ConfirmReturnGoods(entity, ref returnMoney, ref pmoney, ref mmoney);
                        if (returnMoney > 0)
                        {
                            string remoney = (returnMoney * 100).ToString("0");
                            string rt = Refund(order.OrderNo, entity.ReturnNo, (order.PayMoney * 100).ToString("0"), remoney);
                            var res = XDocument.Parse(rt);

                            if (res != null && res.Element("xml") != null)
                            {
                                return_code = res.Element("xml").Element("return_code").Value;
                                //out_trade_no = res.Element("xml").Element("out_trade_no").Value;
                                //transaction_id = res.Element("xml").Element("transaction_id").Value;
                            }
                            if (return_code.ToUpper() == "SUCCESS" && res.Element("xml").Element("err_code") == null)
                            {
                                if (pmoney > 0 || mmoney > 0)
                                {
                                    MemberBalanceDetail mbd = new MemberBalanceDetail();
                                    mbd.Point = 0;
                                    mbd.Amount = 0;

                                    if (pmoney > 0)
                                    {
                                        //member.Points = member.Points + int.Parse((pmoney * 100).ToString("0"));
                                        mbd.Point = int.Parse((pmoney * 100).ToString("0"));
                                    }

                                    if (mmoney > 0)
                                    {
                                        //member.Balance = member.Balance + mmoney;
                                        mbd.Amount = mmoney;
                                    }
                                    //mbd.MemberAmount = member.Balance;
                                    //mbd.MemberPoint = member.Points;
                                    mbd.MemberId = order.MemberId;
                                    mbd.Note = "订单退款返还";
                                    mbd.OrderId = order.Id;
                                    mbd.OrderNo = order.OrderNo;
                                    mbd.AddUserId = CurrentLoginUser.Id;
                                    _memberService.AddMemberBalanceDetail(mbd);
                                    logService.OperationLog(CurrentLoginUser.Id, CurrentLoginUser.UserName, Request.RawUrl,
                                "订单退款返还成功", $"用户Id:{mbd.MemberId},订单Id:{mbd.OrderId},订单号:{mbd.OrderNo},积分:{mbd.Point},金额:{mbd.Amount}。", Generator.GetIP());
                                }
                                _orderService.EditReturnGoods(entity);

                                detail.SendStatus = OrderDetailSendStatus.已退货;
                                _orderService.EditOrderDetail(detail);

                                if (detail.Points > 0)
                                {
                                    MemberBalanceDetail mbd1 = new MemberBalanceDetail();
                                    mbd1.MemberId = member.Id;
                                    mbd1.Point = detail.Points * -1;
                                    mbd1.MemberAmount = member.Balance;
                                    mbd1.MemberPoint = member.Points;
                                    mbd1.Amount = 0;
                                    mbd1.OrderId = model.OrderId;
                                    mbd1.OrderNo = model.OrderNo;
                                    mbd1.Note = "订单退款扣除积分";
                                    _memberService.AddMemberBalanceDetail(mbd1);
                                    logService.OperationLog(CurrentLoginUser.Id, CurrentLoginUser.UserName, Request.RawUrl,
                            "订单退款扣除积分成功", $"用户Id:{mbd1.MemberId},订单Id:{mbd1.OrderId},订单号:{mbd1.OrderNo},积分:{mbd1.Point},金额:{mbd1.Amount}。", Generator.GetIP());
                                }

                                result.isSuccess = true;
                            }
                            else
                            {
                                result.msg = "退款失败";
                                logService.OperationLog(CurrentLoginUser.Id, CurrentLoginUser.UserName, Request.RawUrl,
                            "订单退款失败", $"退款失败", Generator.GetIP());
                                return Json(result);
                            }
                        }
                        else
                        {
                            result.isSuccess = true;
                        }
                    }
                    else
                    {
                        result.msg = "退款金额需大于0";
                        return Json(result);
                    }

                    #endregion
                }
                else
                {
                    if (entity.Satus != ReturnStatus.客服处理中 || entity.Satus != ReturnStatus.待处理)
                    {
                        entity.ReturnAmount = 0;
                    }
                    _orderService.EditReturnGoods(entity);
                }

                if (entity.ReturnType == 0 && entity.Satus == ReturnStatus.已拒绝&&!entity.ReturnResult.HasValue)
                {

                    logService.OperationLog(CurrentLoginUser.Id, CurrentLoginUser.UserName, Request.RawUrl,
                            "拒绝退还货申请", $"将Id为{model.Id}的商品被拒绝退货", Generator.GetIP());
                }
                
                
                
                if (entity.Satus == ReturnStatus.已换货&&detail.SendStatus!=OrderDetailSendStatus.已换货&&detail.SendStatus!=OrderDetailSendStatus.已退货)
                {
                    detail.SendStatus = OrderDetailSendStatus.已换货;
                    _orderService.EditOrderDetail(detail);
                    logService.OperationLog(CurrentLoginUser.Id, CurrentLoginUser.UserName, Request.RawUrl,
                            "同意换货", $"将Id为{model.Id}的商品同意换货", Generator.GetIP());
                }
                result.isSuccess = true;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result);
        }

        public JsonResult ConfirmReturnGoods(ReturnGoods model)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            try
            {
                string return_code = "";
                var entity = _orderService.GetReturnGoodsInfo(model.Id);
                entity.ReturnAmount = model.ReturnAmount;
                entity.ReturnType = model.ReturnType;
                entity.Remark = model.Remark;
                entity.Satus = model.Satus;
                entity.UserId = CurrentLoginUser.Id;

                var member = _memberService.GetMemberInfo(model.MemberId);
                if (entity.ReturnAmount > 0)
                {
                    var order = _orderService.GetOrderInfo(entity.OrderId);
                    

                    decimal returnMoney = 0;
                    decimal pmoney = 0;
                    decimal mmoney = 0;
                    _orderService.ConfirmReturnGoods(entity, ref returnMoney, ref pmoney, ref mmoney);
                    if (returnMoney > 0)
                    {
                        string remoney = (returnMoney * 100).ToString("0");
                        string rt = Refund(order.OrderNo, entity.ReturnNo, (order.PayMoney * 100).ToString("0"), remoney);
                        var res = XDocument.Parse(rt);

                        if (res != null && res.Element("xml") != null)
                        {
                            return_code = res.Element("xml").Element("return_code").Value;
                            //out_trade_no = res.Element("xml").Element("out_trade_no").Value;
                            //transaction_id = res.Element("xml").Element("transaction_id").Value;
                        }
                        if (return_code.ToUpper() == "SUCCESS"  && res.Element("xml").Element("err_code") == null)
                        {
                            if (pmoney > 0 || mmoney > 0)
                            {
                                MemberBalanceDetail mbd = new MemberBalanceDetail();
                                mbd.Point = 0;
                                mbd.Amount = 0;
                               
                                if (pmoney > 0)
                                {
                                    //member.Points = member.Points + int.Parse((pmoney * 100).ToString("0"));
                                    mbd.Point = int.Parse((pmoney * 100).ToString("0"));
                                }

                                if (mmoney > 0)
                                {
                                    //member.Balance = member.Balance + mmoney;
                                    mbd.Amount = mmoney;
                                }
                                //mbd.MemberAmount = member.Balance;
                                //mbd.MemberPoint = member.Points;
                                mbd.MemberId = order.MemberId;
                                mbd.Note = "订单退款返还";
                                mbd.OrderId = order.Id;
                                mbd.OrderNo = order.OrderNo;
                                mbd.AddUserId = CurrentLoginUser.Id;
                                _memberService.AddMemberBalanceDetail(mbd);
                                logService.OperationLog(CurrentLoginUser.Id, CurrentLoginUser.UserName, Request.RawUrl,
                            "订单退款返还成功", $"用户Id:{mbd.MemberId},订单Id:{mbd.OrderId},订单号:{mbd.OrderNo},积分:{mbd.Point},金额:{mbd.Amount}。", Generator.GetIP());
                            }
                            _orderService.EditReturnGoods(entity);

                            var detail = _orderService.FindOrderDetail(entity.OrderDetailId);
                            detail.SendStatus = OrderDetailSendStatus.已退货;
                            _orderService.EditOrderDetail(detail);

                            if(detail.Points > 0)
                            {
                                MemberBalanceDetail mbd1 = new MemberBalanceDetail();
                                mbd1.MemberId = member.Id;
                                mbd1.Point = detail.Points * -1;
                                mbd1.MemberAmount = member.Balance;
                                mbd1.MemberPoint = member.Points;
                                mbd1.Amount = 0;
                                mbd1.OrderId = model.OrderId;
                                mbd1.OrderNo = model.OrderNo;
                                mbd1.Note = "订单退款扣除积分";
                                _memberService.AddMemberBalanceDetail(mbd1);
                                logService.OperationLog(CurrentLoginUser.Id, CurrentLoginUser.UserName, Request.RawUrl,
                        "订单退款扣除积分成功", $"用户Id:{mbd1.MemberId},订单Id:{mbd1.OrderId},订单号:{mbd1.OrderNo},积分:{mbd1.Point},金额:{mbd1.Amount}。", Generator.GetIP());
                            }

                            result.isSuccess = true;
                        }
                        else
                        {
                            result.msg = "退款失败";
                            logService.OperationLog(CurrentLoginUser.Id, CurrentLoginUser.UserName, Request.RawUrl,
                        "订单退款失败", $"退款失败", Generator.GetIP());
                            return Json(result);
                        }
                    }
                    else
                    {
                        result.isSuccess = true;
                    }
                }
                else
                {
                    result.msg = "退款金额需大于0";
                    return Json(result);
                }
                
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result);
        }


        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors == SslPolicyErrors.None)
                return true;
            return false;
        }
        /// <summary>
        /// 退款申请接口
        /// </summary>
        /// <param name="out_trade_no">填入商家订单号</param>
        /// <param name="out_refund_no">填入退款订单号</param>
        /// <param name="total_fee">填入总金额</param>
        /// <param name="refund_fee">填入退款金额</param>
        /// <returns></returns>
        public string Refund(string out_trade_no, string out_refund_no, string total_fee, string refund_fee)
        {
            //string appId = ConfigurationManager.AppSettings["AppId"];
            //string key = ConfigurationManager.AppSettings["Key"];
            //string mchId = ConfigurationManager.AppSettings["MchId"];

            var config = _configService.GetConfig();

            string appId = config.AppId;
            string key = config.PaySignKey;
            string mchId = config.PartnerID;
            string certUrl = Server.MapPath("/cert/apiclient_cert.p12");
            string nonceStr = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("appid", appId); //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId); //商户号
            packageReqHandler.SetParameter("out_trade_no", out_trade_no); //填入商家订单号
            packageReqHandler.SetParameter("out_refund_no", out_refund_no); //填入退款订单号
            packageReqHandler.SetParameter("total_fee", total_fee); //填入总金额
            packageReqHandler.SetParameter("refund_fee", refund_fee); //填入退款金额
            packageReqHandler.SetParameter("op_user_id", mchId); //操作员Id，默认就是商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串
            string sign = packageReqHandler.CreateMd5Sign("key", key);
            packageReqHandler.SetParameter("sign", sign); //签名
            //退款需要post的数据
            string data = packageReqHandler.ParseXML();

            //退款接口地址
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            //本地或者服务器的证书位置（证书在微信支付申请成功发来的通知邮件中）
            string cert = certUrl;
            //私钥（在安装证书时设置）
            string password = mchId;
            ServicePointManager.ServerCertificateValidationCallback =
                new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password,
                X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            #region 发起post请求

            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            #endregion

            var res = XDocument.Parse(responseContent);
            return responseContent;
        }
        #endregion
    }
}